package com.qyer.search.storm.util;

import com.qyer.search.storm.exception.DBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.sql.*;
/**
 * Created by tangzheng on 16/1/11.
 */
public class CountryService {
  private static final Logger LOGGER = LoggerFactory.getLogger(CityService.class);
  private volatile static CountryService singleton;
  private Map<Integer, String> countries;


  private CountryService (Map<String, Object> config, String boltPrefix){
    countries = new HashMap<>();

    String DBurl = String.valueOf(config.get(boltPrefix + "db.country.url"));
    String user = String.valueOf(config.get(boltPrefix + "db.country.user"));
    String pass = String.valueOf(config.get(boltPrefix + "db.country.password"));
    String sql = "select c.id,c.catename from category as c join country as d on c.id = d.id;";

    Connection conn = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      conn = java.sql.DriverManager.getConnection(DBurl, user, pass);
      Statement stmt = conn.createStatement();
      ResultSet res = stmt.executeQuery(sql);
      while (res.next()){
        countries.put(res.getInt(1), res.getString(2));
      }
    }catch (Exception e){
      LOGGER.error("country map get failed,{}", e);
    }finally {
      try {
        if (conn != null) {
          conn.close();
        }
      }catch (Exception ee){
        LOGGER.error(ee.getMessage());
      }
    }
  }
  public static CountryService getInstance(Map<String, Object> config, String boltPrefix) {
    if (singleton == null) {
      synchronized (CountryService.class) {
        if (singleton == null) {
          singleton = new CountryService(config, boltPrefix);
        }
      }
    }
    return singleton;
  }

  public String getCountryName(int id){
    return countries.get(id);
  }

}
